﻿namespace FastColoredTextBoxNS
{
    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    using System.Windows.Forms;

    public partial class ReplaceForm : Form
    {
        private readonly FastColoredTextBox tb;

        private bool firstSearch = true;

        private Place startPlace;

        public ReplaceForm(FastColoredTextBox tb)
        {
            this.InitializeComponent();
            this.tb = tb;
        }

        private void btClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btFindNext_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.Find(this.tbFind.Text))
                {
                    MessageBox.Show("Not found");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public List<Range> FindAll(string pattern)
        {
            RegexOptions opt = this.cbMatchCase.Checked ? RegexOptions.None : RegexOptions.IgnoreCase;
            if (!this.cbRegex.Checked)
            {
                pattern = Regex.Escape(pattern);
            }
            if (this.cbWholeWord.Checked)
            {
                pattern = "\\b" + pattern + "\\b";
            }
            //
            Range range = this.tb.Selection.IsEmpty ? this.tb.Range.Clone() : this.tb.Selection.Clone();
            //
            var list = new List<Range>();
            foreach (var r in range.GetRangesByLines(pattern, opt))
            {
                list.Add(r);
            }

            return list;
        }

        public bool Find(string pattern)
        {
            RegexOptions opt = this.cbMatchCase.Checked ? RegexOptions.None : RegexOptions.IgnoreCase;
            if (!this.cbRegex.Checked)
            {
                pattern = Regex.Escape(pattern);
            }
            if (this.cbWholeWord.Checked)
            {
                pattern = "\\b" + pattern + "\\b";
            }
            //
            Range range = this.tb.Selection.Clone();
            range.Normalize();
            //
            if (this.firstSearch)
            {
                this.startPlace = range.Start;
                this.firstSearch = false;
            }
            //
            range.Start = range.End;
            if (range.Start >= this.startPlace)
            {
                range.End = new Place(this.tb.GetLineLength(this.tb.LinesCount - 1), this.tb.LinesCount - 1);
            }
            else
            {
                range.End = this.startPlace;
            }
            //
            foreach (var r in range.GetRangesByLines(pattern, opt))
            {
                this.tb.Selection.Start = r.Start;
                this.tb.Selection.End = r.End;
                this.tb.DoSelectionVisible();
                this.tb.Invalidate();
                return true;
            }
            if (range.Start >= this.startPlace && this.startPlace > Place.Empty)
            {
                this.tb.Selection.Start = new Place(0, 0);
                return this.Find(pattern);
            }
            return false;
        }

        private void tbFind_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                this.btFindNext_Click(sender, null);
            }
            if (e.KeyChar == '\x1b')
            {
                this.Hide();
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData) // David
        {
            if (keyData == Keys.Escape)
            {
                this.Close();
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void ReplaceForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
            }
            this.tb.Focus();
        }

        private void btReplace_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.tb.SelectionLength != 0)
                {
                    if (!this.tb.Selection.ReadOnly)
                    {
                        this.tb.InsertText(this.tbReplace.Text);
                    }
                }
                this.btFindNext_Click(sender, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btReplaceAll_Click(object sender, EventArgs e)
        {
            try
            {
                this.tb.Selection.BeginUpdate();

                //search
                List<Range> ranges = this.FindAll(this.tbFind.Text);
                //check readonly
                bool ro = false;
                foreach (var r in ranges)
                {
                    if (r.ReadOnly)
                    {
                        ro = true;
                        break;
                    }
                }
                //replace
                if (!ro)
                {
                    if (ranges.Count > 0)
                    {
                        this.tb.TextSource.Manager.ExecuteCommand(
                            new ReplaceTextCommand(this.tb.TextSource, ranges, this.tbReplace.Text));
                        this.tb.Selection.Start = new Place(0, 0);
                    }
                }
                //
                this.tb.Invalidate();
                MessageBox.Show(ranges.Count + " occurrence(s) replaced");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.tb.Selection.EndUpdate();
        }

        protected override void OnActivated(EventArgs e)
        {
            this.tbFind.Focus();
            this.ResetSerach();
        }

        private void ResetSerach()
        {
            this.firstSearch = true;
        }

        private void cbMatchCase_CheckedChanged(object sender, EventArgs e)
        {
            this.ResetSerach();
        }
    }
}